<?php
$tab = $AppUI->getState('QuotationsIdxTab') !== NULL ? $AppUI->getState('QuotationsIdxTab') : 0;
$active = intval(!$AppUI->getState('QuotationsIdxTab'));

// Load quotation object
$obj = new CQuotations();
$quote_id = intval(dPgetParam($_GET, 'quote_id', 0));
// This is line_id
$item_id = intval(dPgetParam($_GET, 'item_id', 0));

// setup the title block with Name, Icon and Help
$ttl = $item_id > 0 ? "Edit Line" : "New Line";
$titleBlock = new CTitleBlock('Quotations: '.$ttl, 'quotations.jpg', $m, "$m.$a");
$titleBlock->addCell();
$titleBlock->addCell(
	'<input type="submit" class="button" value="'.$AppUI->_('quotation list').'">', '',
	'<form action="?m=quotations&tab=0" method="post">', '</form>'
);
//finally show the titleBlock
$titleBlock->show();
$quotationObj = $obj->getQuotationById($uid, $quote_id);
if(!is_array($quotationObj) or count($quotationObj)==0){
	$AppUI->setMsg('Quotations');
	$AppUI->setMsg("invalidID", UI_MSG_ERROR, true);
	$AppUI->redirect("m=quotations");
}
$quotationObj = $quotationObj[0];
// check permissions for this record
//$canEdit = !getDenyEdit($m, $quote_id);
$perms =& $AppUI->acl();
$canEdit = $perms->checkModuleItem($m, 'edit', $quote_id);
$lock_status = 0;

if(isset($quotationObj['quote_completed'])){
	$lock_status = intval($quotationObj['quote_completed']);
}
//$canEdit = 1;
// Check new line
// Check permission edit line
if(!$canEdit or $lock_status) {
	$AppUI->setMsg('Edit Permission Deny', UI_MSG_ERROR);
	$AppUI->redirect(PUBLIC_PAGE);
}

require_once($AppUI->getModuleClass('companies'));
require_once($AppUI->getMasterDataClass('mdtype'));
require_once($AppUI->getMasterDataClass('mdstatus'));
require_once($AppUI->getMasterDataClass('mdunit'));

// instance of Object Line
require_once('quotation_lines.class.php');
$obj = new CQuotation_lines();

$msg = '';
// $canDelete = $obj->canDelete($msg, $quote_id);
$pathQuote = './index.php?m=quotations&tab=0';

// also have a breadcrumb here

$row = null;
if($canEdit and ($item_id > 0)) {
	$obj->load($item_id, false);
	$row = $obj;
	if(is_null($row->qitem_quotation)){
		$AppUI->setMsg('Quotations');
		$AppUI->setMsg("invalidID", UI_MSG_ERROR, true);
		$AppUI->redirect();
		//go back to the calling location
	}
}
$quote_obj = new CQuotations();
$itemList = $quote_obj->getItemsList4AutoCompleter();
// This is field redundant
$quote_customer = 1;
// Part apply_mode
$qitem_auto_mode = false;
$qitem_manual_mode = false;
if(!is_object($row)){
	$qitem_auto_mode = true;
}
else{
	if($row->qitem_apply_mode == AUTO_APPLY_VAL){
		$qitem_auto_mode = true;
	}
	else{
		$qitem_manual_mode = true;
	}
}
$view = '';

// load list unit
$unitObj = new CMdUnit();
//$unitList = getUnitList();
$unitList = $unitObj->loadAllUnit();

$vatTypeArr = dPgetSysVal('QItemVATType');
$vatCodeArr = dPgetSysVal('ItemVATCode');
require_once($AppUI->getModuleClass('companies'));
$com = new CCompany();
$com->load($quotationObj['quote_customer']);

require_once(DP_BASE_DIR."/modules/masterdata/classification/classification.class.php");
$cls = new CMdClassification();
$cls->load($com->company_classification);
?>
<script>
var isExamption = <?=$cls->cls_vat_exemption ? "true" : "false"?>;

function doSelectItem(itemObj) {
	if(itemObj==null){
		$('qitem_item_id').value = '';
		$('qitem_item_autocompleter').value = '';
		$('idItemName').value = '';
		$('idItemVATCode').value = '';
		$('idItemVatType').value = 0;
		$('idItemVatType').disabled = false;
	}
	else{
		$('qitem_item_id').value = itemObj.id;
		$('qitem_item_autocompleter').value = itemObj.code;
		$('idItemName').value = itemObj.name;
		$('idItemVATCode').value = itemObj.vat_code;
		if (isExamption) {
			$('idItemVatType').disabled = true;
			$('idItemVatType').value = 0;
			return;
		}
		if (itemObj.vat_code_value < 0) {
			$('idItemVatType').disabled = true;
			$('idItemVatType').value = 0;
		} else {
			$('idItemVatType').disabled = false;
		}
	}
}
</script>
<form name="editFrm" action="./index.php?m=quotations" method="post">
<input type="hidden" name="dosql" value="do_line_crud" />
<input type="hidden" name="del" value="0" />
<input type="hidden" name="qitem_id" value="<?=$item_id?>" />
<input type="hidden" name="quote_id" value="<?=$quote_id?>" />
<input type="hidden" name="qitem_quotation" value="<?=$quote_id?>" />
<input type="hidden" name="qitem_customer" value="<?=$quote_customer?>" />
<input type="hidden" id="qsave_action" name="qsave_action" value="save" />
<table width="100%" cellspacing="0" cellpadding="4" border="0">
<tbody><tr>
	<td class="tabon">[ <?=@$quotationObj['quote_code']?> ] <?=@$quotationObj['quote_name']?></td>
	<td width="100%"></td>
</tr>
</tbody></table>
<table cellspacing="0" cellpadding="4" border="0" width="100%" class="infopanel">
<tr>
	<td>
		<input class="button" type="submit" name="saveAction" value="<?=$AppUI->_('save');?>"/>
		<input class="button" type="submit" name="saveNewAction" value="<?=$AppUI->_('Save & New');?>" onclick="document.getElementById('qsave_action').value='save_new'; return true;"/>
		<input class="button" type="button" name="cancelAction" value="<?=$AppUI->_('cancel');?>" onclick="doCancel('<?=$pathQuote.'&a=quote_view&quote_id='.$quote_id?>')"/>
	</td>
</tr>
</table>
<table cellspacing="0" cellpadding="5" border="0" style="width:100%" class="subinfopanel">
	<tr>
		<td style="width:400px;" valign="top">
			<table cellspacing="0" cellpadding="2" border="0" style="width:400px;">
				<tr>
					<td align="right" style="width: 100px; padding-top: 6px;"> * <?=$AppUI->_('Code')?></td>
					<td>
						<?= arrayAutoSelectLocalItem($itemList, 'qitem_item', 'style="width: 90%; maxlength="50"', @$row->qitem_item, false, @$row->item_code,'doSelectItem');?>
						<!--
						<input type="text" class="text" name="qitem_code" id="idItemCode" value="<?=@$row->item_code?>" maxlength="50"/>
						<img class="clickable" src="images/treetable.gif" onclick="doShowItemsLiveSearchBox()"/>
						-->
					</td>
				</tr>
				<tr>
					<td align="right"> * <?=$AppUI->_('Name')?></td>
					<td>
						<input type="text" class="text" id="idItemName" value="<?=@$row->item_name?>" maxlength="50" readonly="readonly" autocomplete="off" style="width: 99%;"/>
					</td>
				</tr>
				<tr>
					<td  align="right" nowrap="nowrap"><?=$AppUI->_('VAT Code')?></td>
					<td>
						<input type="text" class="text" id="idItemVATCode" value="<?=@$vatCodeArr[$row->item_vat_code]?>" maxlength="50" readonly="readonly" autocomplete="off" style="width: 99%;"/>
					</td>
				</tr>
				<tr>
					<td  align="right" nowrap="nowrap"><?=$AppUI->_('VAT Type')?></td>
					<td>
						<? echo arraySelect($vatTypeArr,'qitem_vat_type'," id='idItemVatType' class='text' style='width: 250px' " . ($row->item_vat_code < 0 ? "disabled='true'" : ""), @$row->qitem_vat_type)?>
					</td>
				</tr>
				<tr>
					<td align="right" valign="top"><?=$AppUI->_('Remarks')?></td>
					<td colspan="100%">
						<textarea id="qitem_remarks" name="qitem_remarks" rows="14" cols="25" style="width: 99%;"><?=@$row->qitem_remarks?></textarea>
					</td>
				</tr>
			</table>
		</td>
		<td valign="top">
			<div id="applyModeDiv" style="padding-top:7px;"><?=$AppUI->_('Apply Mode')?>&nbsp;&nbsp;
				<label><input type="radio" name="qitem_apply_mode" value="<?=AUTO_APPLY_VAL?>" <?=$qitem_auto_mode?'checked="true"':''?> onclick="changeApplyMode('fixedAmountDiv','figureListTable')"/><?=$AppUI->_('Automatic')?></label>
				<label><input type="radio" name="qitem_apply_mode" value="<?=MANUAL_APPLY_VAL?>" <?=$qitem_manual_mode?'checked="true"':''?> onclick="changeApplyMode('figureListTable','fixedAmountDiv')"/><?=$AppUI->_('Manual')?></label>
			</div>
			<div id="fixedAmountDiv" style="padding-top: 9px;">
				<label><?=$AppUI->_('Fixed Amount')?></label>&nbsp;&nbsp;
				<input type="text" id="qitem_fixed_amount" name="qitem_fixed_amount" value="<?=currencyFormat(@$row->qitem_fixed_amount, $quotationObj['quote_currency'] == CURRENCY_VND_VALUE)?>" size="25" maxlength="20" style="text-align: right;" onkeyup="return (currencyFormat(this, ',', <?=$quotationObj['quote_currency'] == CURRENCY_VND_VALUE ? "''" : "'.'"?>, event))"/>
			</div>
			<table id="figureListTable" cellspacing="0" cellpadding="2" border="0" style="width:200px">
				<thead>
				<tr>
					<td style="padding-top: 10px; padding-bottom: 8px;"><?=$AppUI->_('Quantity')?></td>
					<td style="padding-top: 10px; padding-bottom: 8px"><?=$AppUI->_('Unit')?></td>
					<td style="padding-top: 10px; padding-bottom: 8px"><?=$AppUI->_('Price / Unit')?></td></tr>
				</thead>
				<?php for($i = 0; $i < 10; $i++):?>
				<tr>
					<td><input type="text" name="qitem_figure_list[]" value="<?=@$row->qitem_figure_list[$i]?>" size="12" autocomplete="off" style="text-align: right" onkeyup="return (currencyFormat(this, ',', '.', event))"/></td>
					<td>
						<?php
							$tmp_unit_type = 0;
							$unitList_len = count($unitList);
							$unitType_sel = @$row->qitem_unit_list[$i];
							echo "<select name='qitem_unit_list[]' class='text' style='text-transform: capitalize; width: 140px;'>";
							echo "<option value=''>{$AppUI->_('Select One')}</option>";
							for($j = 0; $j < $unitList_len; $j++){
								if($tmp_unit_type != $unitList[$j]['unit_type']){
									$tmp_unit_type = $unitList[$j]['unit_type'];
									echo "<optgroup label='{$unitList[$j]['type_name']}'>";
								}
								echo "<option value='".$unitList[$j]['unit_id']."'";
								if($unitType_sel and ($unitType_sel == $unitList[$j]['unit_id'])){
									echo ' selected="selected"';
								}
								echo "> {$unitList[$j]['unit_name']}</option>";
								if((($tmp_unit_type != 0) and ($tmp_unit_type != $unitList[$j]['unit_type'])) or ($j == $unitList_len)){
									echo '</optgroup>';
								}
							}
							echo "</select>";
							// arraySelect($unitList, 'qitem_unit_list[]', ' size="1" class="text" ', @$row->qitem_unit_list[$i], true);
						?>
					</td>
					<td><input type="text" name="qitem_price_list[]" value="<?=isset($row->qitem_price_list[$i]) ? currencyFormat(@$row->qitem_price_list[$i], $quotationObj['quote_currency']) : ""?>" size="12" autocomplete="off" style="text-align: right" onkeyup="return (currencyFormat(this, ',', <?=$quotationObj['quote_currency'] == CURRENCY_VND_VALUE ? "''" : "'.'"?>, event))"/></td>
				</tr>
				<?php endfor;?>
			</table>
		</td>
	</tr>
</table>
</form>
<script language="JavaScript" type="text/javascript">
<!-- Call function to show or hide apply mode -->
	<?php if($qitem_auto_mode):	?>
	changeApplyMode('fixedAmountDiv','figureListTable');
	<?php else:?>
	changeApplyMode('figureListTable','fixedAmountDiv');
	<?php endif;?>

	var fquoteCustomerId = new LiveValidation('qitem_fixed_amount');
	fquoteCustomerId.add( Validate.Numericality, {minimum: 1, maximum: 9999999999});

	var fQItem_Remarks = new LiveValidation('qitem_remarks');
	//fQItem_Remarks.add( Validate.Presence);
	fQItem_Remarks.add( Validate.Length, {minimum: 0, maximum: 2048});
	//fQItem_Remarks.add(Validate.Format, {pattern: /^[0-9]+((\,[0-9]{3})*(\.[0-9]{0,4})?)?$/});

	var fQItem_Code = new LiveValidation('qitem_item_autocompleter');
	fQItem_Code.add( Validate.Presence);

	var fQItem_Name = new LiveValidation('idItemName');
	fQItem_Name.add( Validate.Presence);
</script>

